<template>
    <div>
        <!-- 面包屑组件 -->
        <breadcrumb :nav-data="['商品管理','参数列表']"></breadcrumb>
        <el-card>
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false"
                effect="dark">
            </el-alert>
            <el-row>
                <el-col>
                    <span>选择商品分类：</span>
                    <!--级联选择器-->
                    <el-cascader
                        v-model="selectKeys"
                        @change="onCascaderChange"
                        :options="cascaderOptions"
                        :props="cascaderProps"></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" type="border-card" @tab-click="changeTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button @click="addParamsVisible=true" :disabled="isBtnDisabled" type="primary" size="mini">
                        添加参数
                    </el-button>
                    <!--分类列表-->
                    <el-table
                        :data="manyTableData"
                        border
                        style="width: 100%">
                        <!--展开行-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                    :key="index"
                                    v-for="(tag,index) in scope.row.attr_values"
                                    closable
                                    :disable-transitions="false"
                                    @close="onDeleteAttr(scope.row, index)">
                                    {{ tag }}
                                </el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="onAddAttr(scope.row)"
                                    @blur="onAddAttr(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small"
                                           @click="onShowAddAttrInput(scope.row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <!--修改-->
                                <el-button type="primary" size="mini" @click="onEditParams(scope.row)"
                                           icon="el-icon-edit">修改
                                </el-button>
                                <!--删除-->
                                <el-button type="danger" size="mini" @click=onDeleteParams(scope.row)
                                           icon="el-icon-delete">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button @click="addParamsVisible=true" :disabled="isBtnDisabled" type="primary" size="mini">
                        添加属性
                    </el-button>
                    <!--分类列表-->
                    <el-table
                        :data="onlyTableData"
                        border
                        style="width: 100%">
                        <!--展开行-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                    :key="index"
                                    v-for="(tag,index) in scope.row.attr_values"
                                    closable
                                    :disable-transitions="false"
                                    @close="onDeleteAttr(scope.row, index)">
                                    {{ tag }}
                                </el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="onAddAttr(scope.row)"
                                    @blur="onAddAttr(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small"
                                           @click="onShowAddAttrInput(scope.row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <!--修改-->
                                <el-button type="primary" size="mini" @click="onEditParams(scope.row)" icon="el-icon-edit">修改
                                </el-button>
                                <!--删除-->
                                <el-button type="danger" size="mini" @click="onDeleteParams(scope.row)" icon="el-icon-delete">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--添加参数-->
        <el-dialog :title="editParamsId?'编辑'+titleText:'添加'+titleText" :visible.sync="addParamsVisible">
            <el-form :model="addParams" :rules="addParamsRules" ref="addParamsForm" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addParams.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addParamsVisible = false">取 消</el-button>
                <el-button type="primary" @click="onAddParams">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: "Params",
  created() {
    this.getCategoriesData();
  },
  data() {
    return {
      editParamsId: null, //修改参数的id
      //被激活的选项卡名称
      activeName: "many",
      //分类级联选择器
      cascaderOptions: [],
      //分类级联选择器配置项
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //分类级联选择器数据绑定
      selectKeys: [],
      //动态参数的数据
      manyTableData: [],
      //静态属性的数据
      onlyTableData: [],
      //添加参数对话框显示隐藏
      addParamsVisible: false,
      //添加参数表单
      addParams: {
        attr_name: "",
        attr_sel: ""
      },
      //添加参数验证
      addParamsRules: {
        attr_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    //获取分类数据
    async getCategoriesData() {
      let res = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cascaderOptions = res.data;
    },
    //选项卡切换事件
    changeTabClick() {
      console.log(this.activeName);
      this.getCategoriesAttrData();
    },

    //分类级联选择器change事件
    onCascaderChange() {
      console.log("当前被选中的节点id", this.selectKeys);
      //获取当前分类的参数
      this.getCategoriesAttrData();
    },
    //获取分类参数和属性
    async getCategoriesAttrData() {
      //通过selectKeys来确定当前要添加的分类他的父级分类id和分类等级
      if (this.selectKeys.length !== 3) {
        //不是三级分类
        this.onlyTableData = [];
        this.manyTableData = [];
        this.selectKeys = [];
        return this.$message.warning("只允许为三级分类设置参数！");
      }
      let res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      });
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      res.data.forEach(item => {
        item.attr_values = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    //确定添加或者修改参数
    onAddParams() {
      this.$refs.addParamsForm.validate(async valid => {
        //如果valid为true 则表示整个表单内的校验都通过了
        if (!valid) return;
        //通过校验
        let obj;
        let editParamsId = this.editParamsId;
        if (editParamsId) {
          //编辑
          obj = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.editParamsId}`,
            {
              attr_name: this.addParams.attr_name,
              attr_sel: this.activeName
            }
          );
        } else { //添加
          obj = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addParams.attr_name,
            attr_sel: this.activeName
          });
        }
        this.addParams.attr_name = "";
        let res = obj
        if (res.meta.status !== 200 && res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.getCategoriesAttrData();
        this.$message.success(res.meta.msg);
        this.addParamsVisible = false;
      });
    },

    //修改参数
    async onEditParams(row) {
      console.log(row, 11111);
      this.editParamsId = row.attr_id;
      this.addParamsVisible = true;
      let res = await this.$http.get(
        `categories/${this.cateId}/attributes/${this.editParamsId}`
      );
      console.log("点击编辑", res);
      this.addParams.attr_name = res.data.attr_name;
    },

    //删除参数
    async onDeleteParams(row) {
      let result = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      console.log(result);
      if (result !== "confirm") return this.$message.info("取消删除");
      let res = await this.$http.delete(
        `categories/${this.cateId}/attributes/${row.attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.getCategoriesAttrData();
      this.$message.success(res.meta.msg);
    },

    //展示添加属性input框
    onShowAddAttrInput(row) {
      //让当前的添加属性input组件展示
      row.inputVisible = true;
      //当虚拟DOM更新完,并且渲染到真实DOM结构之后 再去执行回调函数函数中的内容
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //更新所有的属性
    async updateAttrValues(row, curAddAttr) {
      //之前所有的属性
      let curAttrVlas = row.attr_values.join(",");
      //通过字符串拼接的形式来去把当前新增的属性给放入要传递给后端的属性字符串中
      let attr_vals = curAddAttr ? curAttrVlas + "," + curAddAttr : curAttrVlas;
      //发起ajax请求
      let res = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: attr_vals
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      //把后端返回的数据更新到原有行数据中,并且同步更新attr_values
      row.attr_vals = res.data.attr_vals;
      row.attr_values = row.attr_vals.split(",");
    },
    //确定为某一个参数添加属性
    onAddAttr(row) {
      //当前输入的内容
      let curAddAttr = row.inputValue;
      row.inputValue = ""; //清空输入框的内容
      row.inputVisible = false;
      //非空验证
      if (curAddAttr.trim().length === 0) return;
      this.updateAttrValues(row, curAddAttr);
    },
    //删除参数的某一个属性
    onDeleteAttr(row, index) {
      row.attr_values.splice(index, 1);
      this.updateAttrValues(row);
    }
  },
  //计算属性
  computed: {
    //当前选中的三级分类id
    cateId() {
      //先取出分类id 因为在之前已经判断过了必须长度为3 所以这边可以直接取值
      return this.selectKeys.length === 3 ? this.selectKeys[2] : null;
    },
    //添加参数按钮禁用启用
    isBtnDisabled() {
      //当前分类是不是三级分类
      return this.selectKeys.length !== 3;
    },
    //添加参数对话框标题文本
    titleText() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    }
  }
};
</script>

<style scoped>
.el-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.el-tag {
  margin-left: 10px;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
}
</style>